// import polyfill from 'es6-promise';
// import fetch from 'isomorphic-fetch';
import fetch from 'dva/fetch';
import Cookie from './mcookie';

const APIDomain = "http://maxfactor.data.social-touch.com/dataApi";  //前两期接口
export const CRMAPIDomain = 'http://maxfactor.data.social-touch.com/crmApi';  //三期接口


function parseJSON(response) {
  return response.json();
}

function check401(response) {
  if (response.status === 401) {
    location.href = "/login.html"
  }
  return response;
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  var opts = options ? options : {};
  opts.headers = {
    'Authorization': Cookie.get('Authorization') || 'Authorization',
    'Content-Type': opts.method && opts.method.toLowerCase() == 'post' ? 'application/x-www-form-urlencoded' : 'application/json',
    "Accept": "*/*",
  }
  opts.mode = "cors";
  let api = url.indexOf("/api/") >= 0 ? url : APIDomain + url;
  //CRMApi
  if(url.indexOf('http://') == 0){
    api = url;
  }
  return fetch(api + (api.substring(api.length - 1) == "?" ? "" : "&") + "type=" + (localStorage.getItem("imgType") || "") + "&usertype=" + encodeURIComponent(localStorage.getItem("imgTypeValue") || "") + "&groupId=" + (localStorage.getItem("gid") || "") + "&t=" + new Date().getTime(), opts)
    .then(checkStatus)
    .then(parseJSON)
    .then(check401)
    .then((data) => ({
      data
    }))
    .catch((err) => ({
      err
    }));
}
